<template>
  <div>
    <Header :isGoBack="false">
      <template v-slot:right>
        <el-dropdown @command="handleCommand">
          <span class="speed">当前语速&nbsp; {{ speed }}x&nbsp;<i class="el-icon-arrow-down el-icon--right"></i></span>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item :command="0.5"> 0.5x</el-dropdown-item>
            <el-dropdown-item :command="0.75">0.75x</el-dropdown-item>
            <el-dropdown-item command="1.0">1.0x</el-dropdown-item>
            <el-dropdown-item :command="1.25">1.25x</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
        <div class="btn" @click="goStudyIndex">返回首页</div>
      </template>
    </Header>
    <div class="study-center study-center-sentence w1200">
      <div class="class-name flex-space-be">
        <div class="mr50 pl20" id="step1">
          <span class="book-name mr30">
            {{
              checkedBookData.edition_name + "-" + checkedBookData.grade_name
            }}
          </span>
          <el-dropdown @command="checkBook">
            <span class="el-dropdown-link">
              换课程
              <i class="el-icon-caret-bottom"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item v-for="(item, index) in classData" :key="item.book_id + '' + index" :command="item">
                {{ item.edition_name }}-{{ item.grade_name }}
              </el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
        <div class="flex-space-be class-name-right pr20" id="step2">
          <div class="progress-box">
            <div class="progress" v-if="modeBookSchedule.length > 0">
              <div class="progress-text flex-space-be mb5">
                <span>
                  {{
                    $store.getters.sentenceCategory[
                      modeBookSchedule[0].category
                    ].title
                  }}
                </span>
                <span>
                  {{ modeBookSchedule[0].progessNum }}%({{
                    modeBookSchedule[0].studyNum
                  }}/{{ modeBookSchedule[0].totalNum }})
                </span>
                <i class="el-icon-caret-bottom"></i>
              </div>
              <div>
                <el-progress :percentage="modeBookSchedule[0].progessNum" :show-text="false"
                  :color="$store.getters.color_main"></el-progress>
              </div>
              <div class="progress-absolute">
                <div class="class-schedule">
                  <ul>
                    <li v-for="item in modeBookSchedule" :key="item.category">
                      <span class="mr20">
                        {{
                          $store.getters.sentenceCategory[item.category].title
                        }}
                      </span>
                      <div class="progress-number">
                        <el-progress :color="$store.getters.color_main" :percentage="item.progessNum"
                          :show-text="false"></el-progress>
                        <span class="ml5 mr5"> {{ item.progessNum }}%</span>
                        <span class="info-number">
                          ({{ item.studyNum }}/{{ item.totalNum }})
                        </span>
                      </div>
                    </li>
                  </ul>
                </div>
                <div class="progress-absolute-more" @click="goProgressCourse">
                  查看课程详细进度
                </div>
              </div>
            </div>
          </div>
          <div class="btn-box">
            <el-button class="button button-bg-primary" @click="goTestCenter">
              测试中心
            </el-button>
          </div>
        </div>
      </div>
      <div class="study-conatiner flex-space-be">
        <div class="intelligent-study study-item mr20" id="step4">
          <div class="intelligent-study-header study-item-header flex-space-be">
            <span>智能学习区</span>
            <span>
              <span class="header-right click" @click="goSentenceBook()">句子本</span>
            </span>
          </div>

          <div class="intelligent-study-container flex-space-be">
            <div class="
                intelligent-study-left
                mr20
                study-cotainer
                intelligent-study-item
              " id="step5">
              <div class="intelligent-study-unit">
                <div class="
                    study-cotainer-title
                    intelligent-item-header
                    flex-space-be
                  ">
                  <span class="title">单元</span>
                  <el-popover placement="bottom-start" trigger="hover">
                    <div class="study-schedule-info">
                      <p>
                        打开进度后，单元名称后面的图标便是各个模块的学习状态，如图所示：
                      </p>
                      <p class="study-schedule">
                        <span class="schedule-icon study-nolearn"></span>
                        <span class="schedule-text ml5 mr10">未学</span>
                        <span class="schedule-icon study-learning my_progress">
                          <el-progress :show-text="false" type="circle" :percentage="66" :width="12" :height="12"
                            :stroke-width="2" :color="$store.getters.color_main"></el-progress>
                        </span>
                        <span class="schedule-text ml5 mr10">正在学</span>
                        <span class="schedule-icon study-quick"></span>
                        <span class="schedule-text ml5 mr10">极速挑战</span>
                        <span class="schedule-icon study-pass"></span>
                        <span class="schedule-text ml5 mr10">通过</span>
                        <span class="schedule-icon study-nopass"></span>
                        <span class="schedule-text ml5 mr10">未通过</span>
                        <!-- <span class="schedule-icon study-ultimate"></span>
                        <span class="schedule-text ml5 mr10">终极挑战</span> -->
                      </p>
                    </div>
                    <img slot="reference" src="@/assets/img/icon/help-normal.png" alt="" />
                  </el-popover>
                </div>
                <div class="study-unit">
                  <div class="scorll-box">
                    <ul class="study-unit-list">
                      <li v-for="unit in unitList" :key="unit.unit_id" :class="checkedUnit == unit.unit_id ? 'checked-unit' : ''
                        " @click="checkUnit(unit)">
                        <el-tooltip effect="dark" :content="unit.unit_name" placement="top"
                          :disabled="unit.unit_name.length <= 9" :open-delay="500">
                          <h5>
                            {{ unit.unit_name }}
                          </h5>
                        </el-tooltip>
                        <div class="study-schedule">
                          <span v-for="unitStatus in unit.word_total_vo_list" :key="unitStatus.category"
                            class="schedule-icon my_progress" :class="statusClass[unitStatus.status]">
                            <el-progress v-if="unitStatus.status == 1" :show-text="false" type="circle" :percentage="75"
                              :color="$store.getters.color_main" :width="12" :height="12"
                              :stroke-width="2"></el-progress></span>
                        </div>
                      </li>
                    </ul>
                  </div>
                </div>
              </div>
            </div>
            <div class="
                intelligent-study-right
                study-cotainer
                intelligent-study-item
              ">
              <div class="study-cotainer-title intelligent-item-header">
                <span>
                  <span> 模块选择 </span>
                  <img class="ml20 click" @click="dialogModeInfo = true" slot="reference"
                    src="@/assets/img/icon/help-normal.png" alt="" />
                </span>
              </div>
              <div class="intelligent-right-conatin">
                <div class="sentence-study">
                  <div class="sentence-study-item" v-for="(modeData, index) in unitModeData" :key="modeData.category">
                    <div class="sentence-study-item-container click" @click="goRoute(modeData)">
                      <!--   -->
                      <div class="sentence-study-item-content">
                        <div class="item-img">
                          <img v-if="modeData.category == 0" src="@/assets/img/sentence-1.png" alt="" />
                          <img v-if="modeData.category == 1" src="@/assets/img/sentence-2.png" alt="" />
                          <img v-if="modeData.category == 2" src="@/assets/img/sentence-3.png" alt="" />
                          <img v-if="modeData.category == 3" src="@/assets/img/sentence-4.png" alt="" />
                        </div>
                        <h4 class="item-title">
                          {{
                            $store.getters.sentenceCategory[modeData.category]
                              .title
                          }}
                        </h4>
                        <div class="item-progress">
                          <el-progress :color="$store.getters.color_main" :percentage="(modeData.studyNum / modeData.totalNum) * 100
                            " :format="() =>
    `${modeData.studyNum ? modeData.studyNum : 0
    } / ${modeData.totalNum}`
    "></el-progress>
                        </div>
                        <p class="study-item-notice" v-if="modeData.reviewNum">
                          需复习：{{ modeData.reviewNum }}
                        </p>
                      </div>
                    </div>
                    <div v-if="index != 3" class="icon-caret-bottom"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="intelligent-review study-item" id="step3">
          <div class="study-item-header">
            <span>智能复习区</span>
          </div>
          <div class="intelligent-review-container">
            <div class="intelligent-review-once">
              <el-button class="button button-bg-second" @click="goReview()">
                一键智能复习
              </el-button>
            </div>
            <ul>
              <li v-for="item in reviewData" :key="item.category" @click="goReview(item)" class="click"
                :class="item.num > 10 ? 'checked-item' : ''">
                {{ $store.getters.sentenceCategory[item.category].title }} (
                {{ item.num }} )
              </li>
            </ul>
          </div>
          <div class="btn-box">
            <el-button class="button button-border-primary" @click="goMemoryReview">
              记忆追踪
            </el-button>
          </div>
        </div>
      </div>
      <el-dialog title="模块说明" :visible.sync="dialogModeInfo">
        <div>
          <div class="mode-item">
            <h4>
              <span class="number">1</span>
              <span class="title">听音组句</span>
              <el-rate disabled :value="3"></el-rate>
            </h4>
            <p>
              通过听读音组句训练，快速提高听力，培养语感，并能积累语法知识。
            </p>
          </div>
          <div class="mode-item">
            <h4>
              <span class="number">2</span>
              <span class="title">听力理解</span>
              <el-rate disabled :value="3"></el-rate>
            </h4>
            <p>通过声音懂含义的训练，提高英语的听写能力。</p>
          </div>
          <div class="mode-item">
            <h4>
              <span class="number">3</span>
              <span class="title">连词成句</span>
              <el-rate disabled :value="3"></el-rate>
            </h4>
            <p>
              通过看句义组句训练，快速提高翻译能力，为英语写作打下坚实基础。
            </p>
          </div>
          <div class="mode-item">
            <h4>
              <span class="number">4</span>
              <span class="title">句子默写</span>
              <el-rate disabled :value="5"></el-rate>
            </h4>
            <p>
              通过看句义写句子训练，提高英语写作能力。这个模块需要有过硬的单词和语法基础，适合英语基础较好的学习者。
            </p>
          </div>
        </div>
      </el-dialog>
    </div>
    <el-dialog title="提示" :visible.sync="checkTypeDialog" @close="questionType = []"
      :width="`${this.checkedBookData.book_id !== 600 ? 600 : 420}px`" center class="question-type">
      <div>
        <el-form v-if="this.checkedBookData.book_id !== 600">
          <el-form-item label="选择题型">
            <el-checkbox-group v-model="questionType">
              <el-checkbox-button :label="1">英译汉</el-checkbox-button>
              <el-checkbox-button :label="2">汉译英</el-checkbox-button>
              <el-checkbox-button :label="3">听力理解</el-checkbox-button>
              <el-checkbox-button :label="4">听写</el-checkbox-button>
              <el-checkbox-button :label="5">默写</el-checkbox-button>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
        <div v-else class="text-center">进入测试</div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="button button-border-primary" @click="goUnitList('generalTest')">普通模式</el-button>
        <el-button class="button button-bg-primary" @click="goUnitList('quickTest')">
          极速模式
        </el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Header from "@/components/Header";
import Driver from "driver.js";
import "driver.js/dist/driver.min.css";
import steps from "@/utils/steps"; //用来存放引导的步骤

import { studyAgain, postStudyAgain } from "@/api/index";
import { getClassData, getUnitList, getReviewNumber } from "@/api/sentence";
/**
 *  typeObj: {
      0: "记忆",
      1: "英译汉",
      2: "汉译英",
      3: "听力理解",
      4: "听写",
      5: "默写",
    },
 */
export default {
  data() {
    return {
      speed: 1.0,
      driver: null,
      checkedUnit: null,
      dialogModeInfo: false,
      unitList: [],
      statusClass: {
        0: "study-nolearn",
        1: "study-learning",
        2: "study-quick",
        3: "study-nopass",
        4: "study-pass",
        5: "study-ultimate",
      },
      checkedBookData: {},
      classData: [],
      reviewData: [],
      checkTypeDialog: false,
      questionType: [],
    };
  },
  computed: {
    unitModeData() {
      let unit = this.unitList.filter((item) => {
        return item.unit_id == this.checkedUnit;
      });
      if (unit && unit.length <= 0) return [];
      return unit[0].unitData;
    },
    isUlimateChalenge() {
      if (!this.unitModeData || this.unitModeData.length == 0) {
        return false;
      }
      return this.unitModeData.every((item) => {
        return item.status >= 4;
      });
    },
    modeBookSchedule() {
      let data = [];
      if (
        this.checkedBookData.word_book_vo_list &&
        this.checkedBookData.word_book_vo_list.length > 0
      ) {
        let totalNum = this.checkedBookData.word_book_vo_list[0].total_number;
        for (let i = 0; i < 4; i++) {
          let indexData = this.checkedBookData.word_book_vo_list.findIndex(
            (item) => {
              return item.source == i;
            }
          );

          if (indexData > -1) {
            data.push({
              totalNum,
              studyNum:
                this.checkedBookData.word_book_vo_list[indexData].study_number,
              category: i,
              number: this.checkedBookData.word_book_vo_list[indexData].number,
            });
          } else {
            data.push({
              totalNum,
              studyNum: 0,
              category: i,
              number: this.checkedBookData.word_book_vo_list[0].number,
            });
          }
        }
      }
      data.forEach((item) => {
        item.progessNum = parseInt((item.studyNum / item.totalNum) * 100);
      });
      data.sort((a, b) => {
        return a.category - b.category;
      });
      return data;
    },
  },
  methods: {
    handleCommand(command) {
      this.speed = command
      localStorage.setItem("SPEED", command)
    },
    againMemoryClick(source) {
      this.$confirm(
        `再学一遍会将此模块的进度重置，请确认是否再学一遍`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          showClose: true,
          distinguishCancelAndClose: true,
        }
      )
        .then(() => {
          let data = {
            bookId: this.checkedBookData.book_id,
            unitId: this.checkedUnit,
            source,
          };
          postStudyAgain(data).then((res) => {
            if (res.code == 200) {
              this.$alert("重置进度成功", "提示");
              this.getClassData();
            }
          });
        })
        .catch(() => { });
    },
    getReviewNumber() {
      getReviewNumber(this.checkedBookData.book_id).then((res) => {
        if (res.code == 200 && res.data) {
          this.reviewData = res.data.filter((item) => {
            return item.num > 0;
          });
        }
      });
    },
    goUnitList(route) {
      this.$router.push({
        name: route,
        query: {
          unitId: this.checkedUnit,
          category: 24,
          questionType:
            this.questionType.length > 0
              ? this.questionType.join(",")
              : [1, 2, 3, 4, 5].join(","),
        },
      });
    },
    // 换课程
    async checkBook(data) {
      if (
        this.checkedBookData &&
        data.book_id != this.checkedBookData.book_id
      ) {
        await this.$store.dispatch("SetTimeEnglish", 1);
      }
      this.checkedBookData = data;
      localStorage.setItem("bookData", JSON.stringify(this.checkedBookData));
      this.getUnitList();
      this.getReviewNumber();
    },
    getUnitList() {
      let params = {
        bookId: this.checkedBookData.book_id,
      };

      getUnitList(params).then((res) => {
        if (res.code == 200 && res.data) {
          res.data.forEach((item) => {
            item.word_total_vo_list.sort((a, b) => {
              return a.category - b.category;
            });
            let data = [];
            // TODO
            item.category_vo_list = [];
            for (let i = 0; i < 4; i++) {
              // 成绩
              let scoreData = item.category_vo_list.filter((item) => {
                return item.category == i;
              });
              // 待复习
              let reviewData = item.unit_vo_list.filter((item) => {
                return item.category == i;
              });
              // 已学
              let studyData = item.total_vo_list.filter((item) => {
                return item.category == i;
              });
              // 总数
              let sumData = item.word_total_vo_list.filter((item) => {
                return item.category == i;
              });
              let objData = {
                category: i,
                studyNum: studyData.length > 0 ? studyData[0].number : 0,
                totalNum: sumData.length > 0 ? sumData[0].word_sum : 0,
                status: sumData.length > 0 ? sumData[0].status : 0,
                reviewNum:
                  reviewData.length > 0 ? reviewData[0].study_number : 0,
                nearScore: scoreData.length > 0 ? scoreData[0].score : null,
              };
              objData.progressNum =
                objData.totalNum <= 0
                  ? 0
                  : objData.studyNum / objData.totalNum > 1
                    ? 100
                    : (objData.studyNum / objData.totalNum) * 100;
              data.push(objData);
            }
            data.sort((a, b) => {
              return a.category - b.category;
            });
            item.unitData = data;
          });
          this.unitList = res.data;
          let index = this.unitList.findIndex((item) => {
            return item.unit_id == this.checkedUnit;
          });
          if (index == -1 && res.data.length > 0) {
            // this.checkedUnit = res.data[0].unit_id;
            this.checkUnit(res.data[0]);
          }
        } else {
          this.unitList = [];
        }
      });
    },
    goRoute(data) {
      if (data.status > 1) {
        this.$confirm(
          `${this.$store.getters.sentenceCategory[data.category].title
          }学习已完成,前往极速挑战`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            showClose: true,
            distinguishCancelAndClose: true,
          }
        )
          .then(() => {
            this.$router.push({
              name: "sentenceTest",
              query: {
                unitId: this.checkedUnit,
                category: data.category,
                mode: 1,
              },
            });
          })
          .catch(() => { });
      } else {
        this.$router.push({
          name: this.$store.getters.sentenceCategory[data.category].route,
          query: {
            unitId: this.checkedUnit,
          },
        });
      }
    },
    goTestChal() {
      this.$confirm(`前往终极挑战`, "提示", {
        confirmButtonText: "极速模式",
        cancelButtonText: "普通模式",
        showClose: true,
        distinguishCancelAndClose: true,
        beforeClose: this.$beforeConfirmClose,
      })
        .then(() => {
          this.$router.push({
            name: "quickTest",
            query: {
              unitId: this.checkedUnit,
              category: 5,
            },
          });
        })
        .catch((type) => {
          if (type != "close") {
            this.$router.push({
              name: "generalTest",
              query: {
                unitId: this.checkedUnit,
                category: 5,
              },
            });
          }
        });
    },
    goTestCenter() {
      this.$router.push({
        name: "sentenceTestCenter",
      });
    },
    goSentenceBook() {
      this.$router.push({
        name: "sentenceBook",
      });
    },
    goStudyIndex() {
      this.$router.push({
        name: "studyIndex",
      });
    },
    goMemoryReview() {
      this.$router.push({
        name: "sentenceMemoryReview",
      });
    },
    goProgressCourse() {
      this.$router.push({
        name: "sentenceProgressCourse",
      });
    },
    formatProgress(data) {
      return function () {
        if (data.status > 2 && (data.nearScore || data.nearScore == 0)) {
          return data.nearScore + "分";
        } else if (data.totalNum) {
          return "" + data.studyNum + "/" + data.totalNum;
        } else {
          return "0 / 0";
        }
      };
    },
    startSteps() {
      this.$nextTick(() => {
        this.driver = new Driver({
          allowClose: false,
          doneBtnText: "完成", //结束按钮的文字
          stageBackground: "#ffffff", //突出显示元素的背景颜色
          nextBtnText: "我知道了", //下一步按钮的文字
          prevBtnText: "上一步", //上一步按钮的文字
          closeBtnText: "关闭", //关闭按钮的文字
          // onHighlightStarted: (Element) => {
          //   console.log(Element);
          // }, //元素即将突出显示时调用
          // onHighlighted: (Element) => {
          //   console.log(Element);
          // }, //元素完全突出显示时调用
          // onDeselected: (Element) => {
          //   console.log(Element);
          // }, //取消选择元素时调用
          // onReset: (Element) => {
          //   console.log(Element);
          // }, //当要清除叠加时调用
          // onNext: (Element) => {
          //   console.log(Element);
          // }, //在任何步骤中移动到下一步时调用
          // onPrevious: (Element) => {
          //   console.log(Element);
          // }, //在任何步骤中移动到上一步时调用
        });
        this.driver.defineSteps(steps);
        this.driver.start();
      });
    },
    goReview(data) {
      if (data) {
        if (data.num > 0) {
          this.$router.push({
            name: this.$store.getters.sentenceCategory[data.category].route,
            query: {
              isReview: true,
            },
          });
        }
      } else {
        let filterData = this.reviewData.filter((item) => {
          return item.num > 0;
        });
        if (filterData.length > 0) {
          this.$router.push({
            name: this.$store.getters.sentenceCategory[filterData[0].category]
              .route,
            query: {
              isReview: true,
            },
          });
        } else {
          this.$alert("暂无可以复习的单词", "提示");
        }
      }
    },
    getClassData() {
      getClassData().then((res) => {
        if (res.code == 200 && res.data) {
          res.data = res.data.filter((item) => {
            return item.status == 0;
          });
          this.classData = res.data.filter((item) => {
            return (
              item.permission == 0 &&
              item.list &&
              item.list[0] &&
              item.list[0].sentence_state
            );
          });
          if (this.classData) {
            let index = this.classData.findIndex((item) => {
              return item.book_id == this.checkedBookData.book_id;
            });
            if (index == -1) {
              this.goStudyIndex();
            } else {
              this.checkBook(this.classData[index]);
            }
          }
        }
      });
    },

    checkUnit(data) {
      this.checkedUnit = data.unit_id;
      localStorage.setItem("checkedUnit", JSON.stringify(data));
    },
    studyAgain(source, number) {
      let isAgain = this.unitList.every((item) => {
        let data = item.word_total_vo_list.filter((status) => {
          return status.category == source;
        });
        return data && data[0].status == 5;
      });
      if (isAgain) {
        this.$confirm(
          `再学一遍会将此模块的所有进度重置，请确认是否再学一遍`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            showClose: true,
            distinguishCancelAndClose: true,
          }
        )
          .then(() => {
            let params = {
              bookId: this.checkedBookData.book_id,
              number,
              source,
            };
            studyAgain(params).then((res) => {
              if (res.code == 200) {
                this.getClassData();
                this.$alert("重置进度成功", "提示");
              }
            });
          })
          .catch(() => { });
      } else {
        this.$alert("请本模块的所有单元通过终极挑战再试", "提示");
      }
    },
  },
  created() {
    this.checkedUnit = localStorage.getItem("checkedUnit")
      ? JSON.parse(localStorage.getItem("checkedUnit")).unit_id
      : null;
    this.checkedBookData = JSON.parse(localStorage.getItem("bookData"));
    this.getClassData();
  },
  beforeDestroy() {
    if (this.driver) {
      this.driver.reset();
    }
  },
  mounted() {
    if(localStorage.getItem("SPEED")){
      this.speed = localStorage.getItem("SPEED")
    }
  },
  components: { Header },
  watch: {},
};
</script>
<style lang="scss" scoped>
.speed {
  color: #f7f7f7;
  display: inline-block;
  height: 40px;
  cursor: pointer;
  border-radius: 4px;
  line-height: 40px;
  padding: 0 24px;
  font-size: 14px;
}

.speed:hover {
  background: rgba(255, 255, 255, 0.2);
  color: #f7f7f7;
}
</style>